package com.sunwayhorizo.health.business.registries.place.query;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.jboss.seam.Component;
import org.jboss.seam.annotations.Name;

import com.sunwayhorizo.health.business.base.query.BaseQuery;
import com.sunwayhorizo.health.business.base.query.BaseQueryLocal;
import com.sunwayhorizo.health.common.ListUtil;
import com.sunwayhorizo.health.common.StrUtil;
import com.sunwayhorizo.health.hl7.common.Hl7Exception;
import com.sunwayhorizo.health.hl7.rim.Place;
import com.sunwayhorizo.health.hl7.rim.Role;
import com.sunwayhorizo.health.hl7.vocabulary.EntityCode;
import com.sunwayhorizo.health.hl7.vocabulary.RoleCode;

@Name("BedQuery")
@Stateless
public class BedQuery extends BaseQuery implements BedQueryLocal  
{
    @PersistenceContext(unitName = "sunwayhealth")
    private EntityManager em;
    
    BaseQueryLocal baseQuery = (BaseQueryLocal)Component.getInstance("BaseQuery");


    @SuppressWarnings("unchecked")
    public List<Role> findBedRoleByWGListOrStatus(List<Object> workGroupIds, String status) throws Hl7Exception
    {
        StringBuilder jbql = new StringBuilder();
        jbql.append(" select r from Role r ");
        String cond = " where r.codeEtsId='" + RoleCode.BED.toString() + "' ";
        if (StrUtil.isNotEmpty(status))
        {
            jbql.append(" left join r.playerEntities p ");
            cond += " and p.statusCode='" + status + "'";
        }
        if (ListUtil.isNotEmpty(workGroupIds))
        {
            cond +=" and (";
            for (int i = 0; i < workGroupIds.size(); i++)
            {
                Long id = (Long) workGroupIds.get(i);
                if (i < workGroupIds.size() - 1)
                {
                    cond +=" r.scoperEntities.entityId=" + id + " or ";
                }
                else
                {
                    cond +=" r.scoperEntities.entityId=" + id + "";
                }
            }
            cond +=")";
        }
        List<Role> list = em.createQuery(jbql.toString()+cond).getResultList();
        return list;
    }


    @SuppressWarnings("unchecked")
    public List<Place> findBedListByWardId(String roomId) throws Hl7Exception
    {
        StringBuilder jpql = new StringBuilder();
        jpql.append(" select plc from Place plc where plc.entityId in");
        jpql.append(" (select r.playerEntities.entityId from Role r ");
        jpql.append(" where r.scoperEntities.entityId=" + roomId + " and r.codeEtsId='" + EntityCode.BED.toString() + "' )");
        jpql.append(" and plc.codeEtsId='" + EntityCode.BED.toString() + "' ");
        List<Place> list = em.createQuery(jpql.toString()).getResultList();
        return list;
    }


    @SuppressWarnings("unchecked")
    public List<Long> findBedRoleIdListByWGOrBedNo(String workGroupId, String bedNo) throws Hl7Exception
    {
        StringBuilder jbql = new StringBuilder();
        String cond = "";
        jbql.append(" select r.roleId from Role r ");
        cond += " where r.codeEtsId='" + RoleCode.BED.toString() + "'";
        if (StrUtil.isNotEmpty(workGroupId))
        {
            cond += " and r.scoperEntities.entityId=?1";
        }
        if (StrUtil.isNotEmpty(bedNo))
        {
            jbql.append(" left join r.playerEntities.entyNamesList ename ");
            cond += " and ename.formatted=?2";
        }
        Query query = em.createQuery(jbql.toString() + cond);
        if (StrUtil.isNotEmpty(workGroupId))
        {
            query.setParameter(1, Long.parseLong(workGroupId));
        }
        if (StrUtil.isNotEmpty(bedNo))
        {
            query.setParameter(2, bedNo);
        }
        List<Long> list = query.getResultList();
        return list;
    }


    @SuppressWarnings({ "unchecked" })
    public List<Role> findBedListByWorkgroupId(String workGroupId, String status) throws Hl7Exception
    {
        StringBuilder jbql = new StringBuilder();
        jbql.append("select r from Role r ");
        String cond = " where r.codeEtsId='" + RoleCode.BED.toString() + "' ";
        if (StrUtil.isNotEmpty(status))
        {
            jbql.append(" left join r.playerEntities p ");
            cond += " and p.statusCode='" + status + "'";
        }

        if (StrUtil.isNotEmpty(workGroupId))
        {
            cond += " and r.scoperEntities.entityId=?1";
        }
        cond += "order by r.roleId asc";
        Query query = em.createQuery(jbql.toString()+cond);
        if (StrUtil.isNotEmpty(workGroupId))
        {
            query.setParameter(1, Long.valueOf(workGroupId));
        }
        List<Role> list = query.getResultList();
        return list;

    }


    @SuppressWarnings("unchecked")
    public List<Place> findBedByBedNo(String bedNo) throws Hl7Exception
    {

        StringBuilder jbql = new StringBuilder();
        jbql.append("select plc from Place plc ,in (plc.entyNamesList) name where plc.classCode='PLC' and ");
        jbql.append("name.formatted ='");
        jbql.append(bedNo);
        jbql.append("' and plc.codeEtsId='BED'");

        Query query = em.createQuery(jbql.toString());
        List<Place> places = query.getResultList();

        return places;

    }


    @SuppressWarnings("unchecked")
    @Override
    public Place findBedByBedNoAndOrgNo(String bedNo, String deptId) throws Hl7Exception
    {
        StringBuilder sb = new StringBuilder(
            "select pl from Place pl ,in (pl.entyNamesList) name where pl.entityId in " +
            "( select p.playerEntities.entityId from Role  p where p.scoperEntities.entityId in ");
        sb.append(" ( select o.playerEntities.entityId  from Role o ");
        sb.append("	where o.codeEtsId='" + EntityCode.ROOM.toString() + "' and o.scoperEntities.entityId=" + deptId + " ) and p.codeEtsId='"
                + EntityCode.BED.toString() + "' ) and pl.codeEtsId='" + EntityCode.BED.toString() + "'");
        sb.append(" and name.formatted ='");
        sb.append(bedNo);
        sb.append("'");
        Query query = em.createQuery(sb.toString());
        List<Place> places = query.getResultList();
        return places.isEmpty() ? null : places.get(0);
    }


    @Override
    public Place findBedByBedNoAndOrgRoleId(String bedNo, String roleId) throws Hl7Exception
    {
        StringBuilder sb = new StringBuilder(
            "select pl from Place pl ,in (pl.entyNamesList) name where pl.entityId in " +
            "( select p.playerEntities.entityId from Role  p where p.scoperEntities.entityId in ");
        sb.append(" ( select o.playerEntities.entityId  from Role o ,in (o.scoperEntities.playerRolesList) role1");
        sb.append("	where "
                // + "o.codeEtsId='" + EntityCode.ROOM.toString()+ "' and"
                + " role1.roleId=" + roleId + " ) and p.codeEtsId='" + EntityCode.BED.toString() + "' ) and pl.codeEtsId='"
                + EntityCode.BED.toString() + "'");
        sb.append(" and name.formatted ='");
        sb.append(bedNo);
        sb.append("'");
        Query query = em.createQuery(sb.toString());

        @SuppressWarnings("unchecked")
        List<Place> places = query.getResultList();
        return places.isEmpty() ? null : places.get(0);
    }


    @Override
    public Place findByRoleId(String roleId) throws  Hl7Exception
    {
        Role role = baseQuery.findRoleById(Long.valueOf(roleId));
        if(null == role) return null;
        Place places = (Place)role.getPlayerEntity();
        if (null != places)
        {
            return places;
        }
        return null;
    }


    @Override
    public Role findBedRoleByBedNoAndWorkGroupRoleId(String bedNo, String roleId) throws Hl7Exception
    {
        StringBuilder jbql = new StringBuilder();
        jbql.append("select distinct r from Role r left join r.scoperEntities.playerRolesList pr ");
        jbql.append("left join r.playerEntities.entyNamesList name ");
        jbql.append("left join name.entyNamePartsList part left join name.entyNameUsesList use ");
        jbql.append(" where r.codeEtsId='BED' ");
        jbql.append(" and part.literal ='");
        jbql.append(bedNo);
        jbql.append("' and pr.roleId=");
        jbql.append(roleId);
        jbql.append(" and use.use='L'");
        @SuppressWarnings("unchecked")
        List<Role> roles = em.createQuery(jbql.toString()).getResultList();
        if (roles.isEmpty())
        {

            return null;
        }
        return roles.get(0);
    }


    @Override
    public Role findBedRoleByBedNoAndWorkGroupEntityId(String bedNo, String entityId) throws Hl7Exception
    {
        StringBuilder jbql = new StringBuilder();
        jbql.append(" select distinct r from Role r left join r.scoperEntities pr ");
        jbql.append(" left join r.playerEntities.entyNamesList name ");
        jbql.append(" left join name.entyNamePartsList part ");
        jbql.append(" left join name.entyNameUsesList use ");
        jbql.append(" where r.codeEtsId='BED' ");
        jbql.append(" and part.literal ='");
        jbql.append(bedNo);
        jbql.append("' and pr.entityId=");
        jbql.append(entityId);
        jbql.append("  and use.use='L'");
        @SuppressWarnings("unchecked")
        List<Role> roles = em.createQuery(jbql.toString()).getResultList();
        if (roles.isEmpty())
        {
            return null;
        }
        return roles.get(0);
    }

    @Override
    public Role findBedRoleByBedNoAndWorkGroupCode(String bedNo, String workgroupCode) throws Hl7Exception
    {
        StringBuilder jbql = new StringBuilder();
        jbql.append("select distinct r from Role r left join r.scoperEntities.playerRolesList pr ");
        jbql.append("left join r.playerEntities.entyNamesList name ");
        jbql.append("left join name.entyNamePartsList part left join name.entyNameUsesList use ");
        jbql.append("left join pr.roleIiList rii ");
        jbql.append(" where r.codeEtsId='BED' ");
        jbql.append(" and part.literal ='");
        jbql.append(bedNo);
        jbql.append("' and rii.extensionTxt='");
        jbql.append(workgroupCode);
        jbql.append("' and use.use='L'");
        @SuppressWarnings("unchecked")
        List<Role> roles = em.createQuery(jbql.toString()).getResultList();
        if (roles.isEmpty())
        {

            return null;
        }
        return roles.get(0);
    }

}
